package com.sxygsj.android.personnelscreen.plugin_jiguang.main

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shencoder.pagergridlayoutmanager.PagerGridLayoutManager
import com.sxygsj.android.personnelscreen.plugin_jiguang.R
import com.sxygsj.android.personnelscreen.plugin_jiguang.htppCallBack.HttpCallBackEntity
import com.sxygsj.android.personnelscreen.plugin_jiguang.userInfoList.UserInfo
import com.sxygsj.android.personnelscreen.plugin_jiguang.userInfoList.UserInfoListAdapter
import com.sxygsj.android.personnelscreen.plugin_jiguang.userInfoList.UserInfoListFragment
import com.sxygsj.android.personnelscreen.plugin_jiguang.webserver.WebServerService
import com.tencent.mmkv.MMKV
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.collections.ArrayList

public class MainActivity : AppCompatActivity() {



    private lateinit var title:TextView
    private lateinit var recyclerView:RecyclerViewForEmpty
    private lateinit var emptyView:EmptyView
    private val adapter: UserInfoListAdapter by lazy { UserInfoListAdapter() }

    companion object {

        lateinit var ShiftLeader: TextView
        lateinit var DutyLeader: TextView
        lateinit var roll: MarqueeView
        private val layoutManager: PagerGridLayoutManager by lazy {
            PagerGridLayoutManager(
                4,
                4,
                PagerGridLayoutManager.VERTICAL
            )
        }
        var masterServerIP = "172.16.128.101:8089"
        var standbyServerIP = "172.16.128.101:8089"
        var scrollPlaybackSpeed: Float = 3.0f
        var mAdvertisingSwitchingTime: Int = 0
        var advertisingScreenTitle = "集广煤业检卡装置"

        var cardReaderNumber="0005793C"
        var distance=7
        var pageIntervalTime=5L
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        MMKV.initialize(this)
        super.onCreate(savedInstanceState)

        val mmkv = MMKV.mmkvWithID("configureInfo")!!
        masterServerIP = mmkv.decodeString("masterServer", "172.16.128.101:8089")!!
        standbyServerIP = mmkv.decodeString("standbyServer", "172.16.128.100:8089")!!
        scrollPlaybackSpeed = mmkv.decodeFloat("standbyServer", 3.0f)
        mAdvertisingSwitchingTime = mmkv.decodeInt("mAdvertisingSwitchingTime", 10)
        advertisingScreenTitle = mmkv.decodeString("advertisingScreenTitle", "集广煤业检卡装置")!!


        startService(Intent(this, WebServerService::class.java))
        setContentView(R.layout.activity_main)

        ShiftLeader = findViewById(R.id.main_tv_ShiftLeader)
        DutyLeader = findViewById(R.id.main_tv_DutyLeader)
        roll = findViewById(R.id.main_tv_roll)
        roll.setTextSize(50.0f)
        recyclerView = findViewById(R.id.main_recyclerView)
        emptyView=findViewById(R.id.main_emptyView)
      //  recyclerView.layoutManager=layoutManager
        recyclerView.adapter=adapter
        recyclerView.setEmptyView(emptyView)
        title= findViewById(R.id.main_tv_title)
        title.setText(advertisingScreenTitle)
        roll.setTextSpeed(scrollPlaybackSpeed)




    }


    override fun onResume() {
        super.onResume()
        requestLeaderConfig(masterServerIP)
        requestLeaderConfig(standbyServerIP)
        requestUserInfo(masterServerIP)
        requestUserInfo(standbyServerIP)
    }
    private fun requestLeaderConfig(ip: String) {
        OkGo.post<String>("http://${ip}/listCheckCardMineInfo")
            .upJson("{}")
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    val json = response!!.body()
                    val httpCallBack = Gson().fromJson<HttpCallBackEntity<List<LeaderConfig>>>(
                        json,
                        object : TypeToken<HttpCallBackEntity<List<LeaderConfig>>>() {}.type
                    )

                    if (httpCallBack != null && httpCallBack.code == 0 && httpCallBack.msg.equals("查询成功")) {
                        val data = httpCallBack.data
                        val leaderConfig = data[0]
                        val string = "带班领导：${leaderConfig.leadLeader}"
                        val DutyLeader_String = "值班领导：${leaderConfig.dutyLeader}"
                        val departmentInfo = "入井人数：${data[0].inMineNum};${data[0].departmentInfo}"
                        if (string != ShiftLeader.text.toString()) {
                            ShiftLeader.setText(string)
                        }
                        if (DutyLeader_String != DutyLeader.text.toString()) {
                            DutyLeader.setText(DutyLeader_String)
                        }

                        if (departmentInfo != roll.text) {
                            roll.setText(departmentInfo)
                        }


                    }
                    requestLeaderConfig(ip)
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    requestLeaderConfig(ip)
                }
            })
    }


    fun requestUserInfo(ip: String) {

        val weakHashMap = WeakHashMap<String, String>()
        weakHashMap["CardReaderID"] = cardReaderNumber
        weakHashMap["Distance"] = distance.toString()
        OkGo.post<String>("http://${ip}/listCheckCard")
            .upJson(Gson().toJson(weakHashMap))
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    val json = response!!.body()
                    val httpCallBack = Gson().fromJson<HttpCallBackEntity<List<UserInfo>>>(
                        json,
                        object : TypeToken<HttpCallBackEntity<List<UserInfo?>?>>() {}.type
                    )
                    if (httpCallBack.code == 0 && httpCallBack.msg.equals("查询成功")) {
                        val copyOnWriteArrayList = CopyOnWriteArrayList<UserInfo>()
                        copyOnWriteArrayList.addAll(httpCallBack.data)
                        adapter.currentList.forEach {
                            Log.e("TAG","=${it.personName}=")
                        }
                        adapter.submitList(copyOnWriteArrayList)

                        val size = adapter.currentList.size
                        if (size > 16) {
                            var page = size / 16
                            val i = size % 16
                            if (i > 0) {
                                page = page + 1
                            }
                            object : CountDownTimer(
                                UserInfoListFragment.pageIntervalTime * 1000,
                                page.toLong() * UserInfoListFragment.pageIntervalTime * 1000
                            ) {
                                override fun onTick(p0: Long) {
                                    layoutManager.scrollToNextPager()
                                }

                                override fun onFinish() {
                                    requestUserInfo(ip)
                                }
                            }.start()
                        } else {
                            requestUserInfo(ip)
                        }
                    } else {
                        requestUserInfo(ip)
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    requestUserInfo(ip)
                }

            })
    }

    override fun onDestroy() {
        super.onDestroy()
        recyclerView.layoutManager=null;
    }

}